<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java,concurrent," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="Synchronize实现在java中通过最常用的加锁同步的方式大概就是Synchronize。java通过一对Monitor指令（monitorenter/monitorexit）来实现Synchronize同步功能   那么java又是怎样实现Monitor？任何java对象都有一个monitor与之关联，当一个monitor被持有后，对象就处于锁定状态。在JDK1.6以前，JVM完全依赖操作">
<meta name="keywords" content="java,concurrent">
<meta property="og:type" content="article">
<meta property="og:title" content="java并发编程之Synchronize">
<meta property="og:url" content="https://gitee.com/shuhao/2018/07/05/java并发编程之Synchronize/index.html">
<meta property="og:site_name" content="Niki">
<meta property="og:description" content="Synchronize实现在java中通过最常用的加锁同步的方式大概就是Synchronize。java通过一对Monitor指令（monitorenter/monitorexit）来实现Synchronize同步功能   那么java又是怎样实现Monitor？任何java对象都有一个monitor与之关联，当一个monitor被持有后，对象就处于锁定状态。在JDK1.6以前，JVM完全依赖操作">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://gitee.com/blog/images/java/concurrenty/synchronize_1.png">
<meta property="og:image" content="https://gitee.com/blog/images/java/concurrenty/synchronize_2.png">
<meta property="og:image" content="https://gitee.com/blog/images/java/concurrenty/synchronize_3.png">
<meta property="og:updated_time" content="2018-08-10T07:52:16.617Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java并发编程之Synchronize">
<meta name="twitter:description" content="Synchronize实现在java中通过最常用的加锁同步的方式大概就是Synchronize。java通过一对Monitor指令（monitorenter/monitorexit）来实现Synchronize同步功能   那么java又是怎样实现Monitor？任何java对象都有一个monitor与之关联，当一个monitor被持有后，对象就处于锁定状态。在JDK1.6以前，JVM完全依赖操作">
<meta name="twitter:image" content="https://gitee.com/blog/images/java/concurrenty/synchronize_1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/shuhao/2018/07/05/java并发编程之Synchronize/"/>





  <title> java并发编程之Synchronize | Niki </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb9f0585e406f878cb2f29c89ad3cdb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Niki</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天道酬勤</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-categories"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/shuhao/blog/2018/07/05/java并发编程之Synchronize/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Fang ShuHao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Niki">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                java并发编程之Synchronize
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-07-05T08:28:43+08:00">
                2018-07-05
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/java/" itemprop="url" rel="index">
                    <span itemprop="name">java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="Synchronize实现"><a href="#Synchronize实现" class="headerlink" title="Synchronize实现"></a>Synchronize实现</h2><p>在java中通过最常用的加锁同步的方式大概就是Synchronize。<br>java通过一对Monitor指令（monitorenter/monitorexit）来实现Synchronize同步功能</p>
<img src="/blog/images/java/concurrenty/synchronize_1.png">
<img src="/blog/images/java/concurrenty/synchronize_2.png">
<p>那么java又是怎样实现Monitor？<br>任何java对象都有一个monitor与之关联，当一个monitor被持有后，对象就处于锁定状态。<br>在JDK1.6以前，JVM完全依赖操作系统内部的互斥锁来实现Monitor。因此在使用Synchronize时会有一个<strong>用户态到内核态的切换</strong>。这是一个重量级的操作，这也是Synchronize性能被诟病的主要原因。<br>还有一个原因，没有竞争到锁的线程会被阻塞挂起，直到锁释放后，被唤醒，等待竞争锁。线程的阻塞唤醒需要时间，影响了程序的及时响应。</p>
<h2 id="Synchronize改进"><a href="#Synchronize改进" class="headerlink" title="Synchronize改进"></a>Synchronize改进</h2><p>之前有说Synchronize在1.6以前依赖操作系统内部的互斥锁来实现其同步功能。那么在jdk1.6以后java大叔们对其做了什么优化？<br>自jdk1.6以后，java对Synchronize做了比较大的优化，最开始并不是直接由重量级锁实现，最开始为<strong>偏斜锁</strong>，当偏斜锁性能无法满足并发要求时再进行锁升级至<strong>轻量级锁</strong>，再进一步升级至<strong>重量级锁</strong>。</p>
<p>对象锁的类型保存在java对象的Mard Word里存储的锁标志位上。<br><img src="/blog/images/java/concurrenty/synchronize_3.png"></p>
<h3 id="偏斜锁"><a href="#偏斜锁" class="headerlink" title="偏斜锁"></a>偏斜锁</h3><p>在锁对象的对象头Mark Word部分设置线程Id，表示该对象偏向该线程。这种情况并不真正涉及到互斥操作。这种方式的前提是，对象生命周期内，最多被一个线程用于，因此不存在竞争互斥的情况。使用偏斜锁减少竞争开销。</p>
<p><a href="http://shuhao.gitee.io/blog/2018/06/23/Java%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%BB%84%E6%88%90%EF%BC%8C%E5%A6%82%E4%BD%95%E8%AE%A1%E7%AE%97%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%A4%A7%E5%B0%8F/" target="_blank" rel="external">关于对象头可参考</a></p>
<h3 id="轻量级锁"><a href="#轻量级锁" class="headerlink" title="轻量级锁"></a>轻量级锁</h3><p>当有另外的线程试图锁定已经被偏斜的对象时，就出现了互斥竞争。这个时候JVM就会撤销偏斜锁，切换为轻量级锁。轻量级锁利用CAS修改Mark Word来获得锁。</p>
<h3 id="重量级锁"><a href="#重量级锁" class="headerlink" title="重量级锁"></a>重量级锁</h3><p>当互斥竞争越来越激烈时。激烈的竞争会导致大量的线程进行CAS，占用大量的CPU时间（如果是单核的话，则会导致其他线程无法运行，则无法释放锁，类似达到死锁），导致其他线程无法获得CPU时间执行。因此JVM撤销轻量级锁，缓存重量级锁。让所有竞争的线程挂起等待。释放CPU资源。这样做带来的坏处就是。线程的挂起产生的休眠唤醒操作首先需要消耗更多系统资源，另外也使得线程获取锁的时间更长，导致响应性不高。<br>也只有到线程挂起与唤醒花费的时间小于线程自旋获取到锁花费的时间，才切换至重量级锁。</p>
<h3 id="三种状态对比"><a href="#三种状态对比" class="headerlink" title="三种状态对比"></a>三种状态对比</h3><table>
<thead>
<tr>
<th>锁</th>
<th>有点</th>
<th>缺点</th>
<th>使用场景</th>
</tr>
</thead>
<tbody>
<tr>
<td>偏斜锁</td>
<td>加锁和解锁不需要额外消耗，和执行费同步方法比仅存在纳秒级差距</td>
<td>如果存在线程之间的竞争，会带来额外的锁撤销消耗</td>
<td>适用于只有一个线程访问的同步场景</td>
</tr>
<tr>
<td>轻量级锁</td>
<td>竞争的线程不会阻塞，提高程序的响应速度</td>
<td>如果竞争激烈，时钟得不到锁竞争的线程会一直采用自旋消耗CPU</td>
<td>追求响应时间，锁占用时间短</td>
</tr>
<tr>
<td>重量级锁</td>
<td>线程竞争不使用自旋，不会消耗CPU</td>
<td>线程阻塞，响应时间长</td>
<td>追求吞吐量，锁占用时间较长</td>
</tr>
</tbody>
</table>
<h2 id="Synchronize与Lock的对比"><a href="#Synchronize与Lock的对比" class="headerlink" title="Synchronize与Lock的对比"></a>Synchronize与Lock的对比</h2><p>我们知道jdk1.5中java推出了一套新的并发加锁机制Lock。为同步提供了另一个思路。那么Synchronize与Lock相比，我们该如何进行选择呢？<br>ReentrantLock（Lock实现）在实现与Synchronize相同的加锁语义时，还提供了<strong>定时锁、可中断锁、公平锁以及实现非块结构加锁。</strong>并且在jdk1.6以前ReentrantLock在性能谁给你远胜Synchronize（jdk1.6以后Synchronize进行了优化）。那么我们是不是应该抛弃Synchronize转而使用ReentrantLock？<br>与ReentrantLock这样的显示锁相比，Synchronize这种内置锁也有其特有的优势：无需手动释放锁（没有释放，则会埋下隐患）。并且Synchronize在线程转储过程中能给出在那些调用栈中获得了哪些锁，并能够检测和识别发生死锁的线程。对于显示锁，JVM并不知道那些线程持有ReentrantLock。所以在遇到线程问题时，Synchronize显然比ReentrantLock更好排查。<br>由于Synchronize是JVM的内置属性。所以JVM在jdk1.6以后实现了对Synchronize的一些优化，例如：对线程封闭的锁对象的锁消除优化（偏斜锁），通过增加锁的粒度来消除内置锁的同步等方式优化Synchronize（轻量级，重量级锁）。<br>所以未来对Synchronize的优化可能还会继续。所以在进行选择时，如果需要用到加锁的一些高级功能，如：公平锁，可中断锁等可以考虑使用ReentrantLock，在大部分常规应用中，还是推荐使用Synchronize。</p>
<blockquote>
<blockquote>
<p>参考<br><a href="https://blog.csdn.net/zishan0072009/article/details/76285995" target="_blank" rel="external">Synchronized下的三种锁升级场景解读</a><br><a href="https://blog.csdn.net/u012715840/article/details/58247556" target="_blank" rel="external">synchronize的实现原理</a><br>[Java并发编程第13章-显示锁]</p>
</blockquote>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/java/" rel="tag"># java</a>
          
            <a href="/blog/tags/concurrent/" rel="tag"># concurrent</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/07/03/HTTP的Header里的Content-Type/" rel="next" title="Header里的Content-Type">
                <i class="fa fa-chevron-left"></i> Header里的Content-Type
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/07/05/VisualVM无法检测到本地java程序/" rel="prev" title="VisualVM无法检测到本地java程序">
                VisualVM无法检测到本地java程序 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNjY5NS8xMzIzMA=="></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/head.jpg"
               alt="Fang ShuHao" />
          <p class="site-author-name" itemprop="name">Fang ShuHao</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">135</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">93</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Synchronize实现"><span class="nav-number">1.</span> <span class="nav-text">Synchronize实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Synchronize改进"><span class="nav-number">2.</span> <span class="nav-text">Synchronize改进</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#偏斜锁"><span class="nav-number">2.1.</span> <span class="nav-text">偏斜锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#轻量级锁"><span class="nav-number">2.2.</span> <span class="nav-text">轻量级锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#重量级锁"><span class="nav-number">2.3.</span> <span class="nav-text">重量级锁</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三种状态对比"><span class="nav-number">2.4.</span> <span class="nav-text">三种状态对比</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Synchronize与Lock的对比"><span class="nav-number">3.</span> <span class="nav-text">Synchronize与Lock的对比</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fang ShuHao</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  



  
  

  

  

  

  


  

</body>
</html>
